package toolsimpl

import (
	"go-caipu/pkg/services/tools"
	"go-caipu/pkg/services/tools/models"
	"gorm.io/gorm"
	"strings"
)

func (s Service) GetSysTablesPage(cmd tools.SysTableSearch) ([]models.SysTables, int64, error) {
	var data models.SysTables
	return data.GetPage(s.store, cmd.GetPageSize(), cmd.GetPageIndex())
}
func (s Service) GetSysTable(tabledId int) (models.SysTables, error) {
	var data models.SysTables
	data.TableId = tabledId
	return data.Get(s.store, true)

}
func (s Service) GetSysTableByTableName(tableName string) (models.SysTables, error) {
	var data models.SysTables
	data.TBName = tableName
	return data.Get(s.store, true)
}

// GetSysTablesTree  获取表格树
func (s Service) GetSysTablesTree() ([]models.SysTables, error) {
	var data models.SysTables
	return data.GetTree(s.store)
}

func (s Service) InsertSysTables(cmd tools.InsertSysTableCmd) (err error) {

	tablesList := cmd.Tables
	tx := s.store.Begin()
	defer func() {
		if err != nil {
			tx.Rollback()
		}
		tx.Commit()
	}()
	for i := 0; i < len(tablesList); i++ {
		data, err := genTableInit(tx, tablesList, i, s.cfg.DbCfg.DbName)
		if err != nil {
			return err
		}
		_, err = data.Create(tx)
		if err != nil {
			return err
		}
	}
	return nil
}

func genTableInit(tx *gorm.DB, tablesList []string, i int, db_name string) (models.SysTables, error) {
	var data models.SysTables
	var dbTable models.DBTables
	var dbColumn models.DBColumns
	data.TBName = tablesList[i]
	data.CreateBy = 0

	dbTable.TableName = data.TBName
	dbTable.DbName = db_name
	dbtable, err := dbTable.Get(tx)
	if err != nil {
		return data, err
	}

	dbColumn.TableName = data.TBName
	tablenamelist := strings.Split(dbColumn.TableName, "_")
	for i := 0; i < len(tablenamelist); i++ {
		strStart := string([]byte(tablenamelist[i])[:1])
		strend := string([]byte(tablenamelist[i])[1:])
		// 大驼峰表名 结构体使用
		data.ClassName += strings.ToUpper(strStart) + strend
		// 小驼峰表名 js函数名和权限标识使用
		if i == 0 {
			data.BusinessName += strings.ToLower(strStart) + strend
		} else {
			data.BusinessName += strings.ToUpper(strStart) + strend
		}
		//data.PackageName += strings.ToLower(strStart) + strings.ToLower(strend)
		//data.ModuleName += strings.ToLower(strStart) + strings.ToLower(strend)
	}
	//data.ModuleFrontName = strings.ReplaceAll(data.ModuleName, "_", "-")
	data.PackageName = "app"
	data.TplCategory = "crud"
	data.Crud = true
	// 中横线表名称，接口路径、前端文件夹名称和js名称使用
	data.ModuleName = strings.Replace(data.TBName, "_", "-", -1)
	dbColumn.DbName = db_name // by 2023-11-1 外面传入
	dbcolumn, err := dbColumn.GetList(tx)
	data.CreateBy = 0
	data.TableComment = dbtable.TableComment
	if dbtable.TableComment == "" {
		data.TableComment = data.ClassName
	}

	data.FunctionName = data.TableComment
	//data.BusinessName = data.ModuleName
	data.IsLogicalDelete = 1
	data.LogicalDelete = true
	data.LogicalDeleteColumn = "is_del"
	data.IsActions = 2
	data.IsDataScope = 1
	data.IsAuth = 1

	data.FunctionAuthor = "go-cpu"
	for i := 0; i < len(dbcolumn); i++ {
		var column models.SysColumns
		column.ColumnComment = dbcolumn[i].ColumnComment
		column.ColumnName = dbcolumn[i].ColumnName
		column.ColumnType = dbcolumn[i].ColumnType
		column.Sort = i + 1
		column.IsInsert = true
		column.QueryType = "EQ"
		column.IsPk = false

		namelist := strings.Split(dbcolumn[i].ColumnName, "_")
		for i := 0; i < len(namelist); i++ {
			strStart := string([]byte(namelist[i])[:1])
			strend := string([]byte(namelist[i])[1:])
			column.GoField += strings.ToUpper(strStart) + strend
			if i == 0 {
				column.JsonField = strings.ToLower(strStart) + strend
			} else {
				column.JsonField += strings.ToUpper(strStart) + strend
			}
		}
		if strings.Contains(dbcolumn[i].ColumnKey, "PR") {
			column.IsPk = true
			data.PkColumn = dbcolumn[i].ColumnName
			//column.GoField = strings.ToUpper(column.GoField)
			//column.JsonField = strings.ToUpper(column.JsonField)
			data.PkGoField = column.GoField
			data.PkJsonField = column.JsonField
		}
		column.IsRequired = false
		if strings.Contains(dbcolumn[i].IsNullable, "NO") {
			column.IsRequired = true
		}

		if strings.Contains(dbcolumn[i].ColumnType, "int") {
			if strings.Contains(dbcolumn[i].ColumnKey, "PR") {
				column.GoType = "int"
			} else {
				column.GoType = "string"
			}
			column.HtmlType = "input"
		} else if strings.Contains(dbcolumn[i].ColumnType, "timestamp") {
			column.GoType = "time.Time"
			column.HtmlType = "datetime"
		} else if strings.Contains(dbcolumn[i].ColumnType, "datetime") {
			column.GoType = "time.Time"
			column.HtmlType = "datetime"
		} else {
			column.GoType = "string"
			column.HtmlType = "input"
		}

		data.Columns = append(data.Columns, column)
	}
	return data, err
}

// UpdateSysTable 更新系统表
func (s Service) UpdateSysTable(table models.SysTables) (models.SysTables, error) {
	return table.Update(s.store)
}

// RemoveSysTable 删除表结构
func (s Service) RemoveSysTable(ids []int) (bool, error) {
	var data models.SysTables
	return data.BatchDelete(s.store, ids)
}
